package com.ebo.agora.openvcall.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.ebo.agora.openvcall.model.ConstantApp;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import http_utils.interfaces.IHttpPostListener;
import http_utils.utils.Ipost;
import http_utils.utils.URLs;
import io.agora.openvcall.R;
import utils.DensityUtil;
import utils.Lg;

public class MainActivity extends BaseActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 隐藏标题栏
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //隐藏虚拟按键
        DensityUtil.setHideVirtualKey(getWindow());

        Intent i = getIntent();
        channel_name = i.getStringExtra("channel_name");
        uid = i.getStringExtra("uid");
        forwardToRoom(channel_name, uid);
    }

    @Override
    protected void initUIandEvent() {
        EditText v_channel = (EditText) findViewById(R.id.channel_name);
        v_channel.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                boolean isEmpty = TextUtils.isEmpty(s.toString());
                findViewById(R.id.button_join).setEnabled(!isEmpty);
            }
        });
        Spinner encryptionSpinner = (Spinner) findViewById(R.id.encryption_mode);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.encryption_mode_values, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        encryptionSpinner.setAdapter(adapter);
        encryptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                vSettings().mEncryptionModeIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        encryptionSpinner.setSelection(vSettings().mEncryptionModeIndex);
        String lastChannelName = vSettings().mChannelName;
        if (!TextUtils.isEmpty(lastChannelName)) {
            v_channel.setText(lastChannelName);
            v_channel.setSelection(lastChannelName.length());
        }
        EditText v_encryption_key = (EditText) findViewById(R.id.encryption_key);
        String lastEncryptionKey = vSettings().mEncryptionKey;
        if (!TextUtils.isEmpty(lastEncryptionKey)) {
            v_encryption_key.setText(lastEncryptionKey);
        }
    }

    @Override
    protected void deInitUIandEvent() {
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_settings:
                forwardToSettings();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void onClickJoin(View view) {
        forwardToRoom();
    }

    //LGY start
    private void forwardToRoom(String channel_name, String uid) {
        Map<String, Object> postParams = new HashMap<String, Object>();
        postParams.put("room_name", channel_name);
        postParams.put("user_id", uid);
        Ipost.send(this, URLs.AGORA_CHANNELKEY, postParams, new PostChannelKey(), false);
    }


    public void forwardToRoom() {
        EditText v_channel = (EditText) findViewById(R.id.channel_name);
        channel_name = v_channel.getText().toString();
        vSettings().mChannelName = channel_name;
        EditText v_encryption_key = (EditText) findViewById(R.id.encryption_key);
        String encryption = v_encryption_key.getText().toString();
        EditText v_uid = (EditText) findViewById(R.id.editText_uid);
        uid = v_uid.getText().toString();
        vSettings().mEncryptionKey = encryption;
        Map<String, Object> postParams = new HashMap<String, Object>();
        postParams.put("room_name", channel_name);
        postParams.put("user_id", uid);
        Ipost.send(this, URLs.AGORA_CHANNELKEY, postParams, new PostChannelKey(), false);
    }

    class PostChannelKey implements IHttpPostListener {
        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(MainActivity.this, result)) {
                return;
            }
            Lg.d("result= " + result);
            if (null != result) {
                try {
                    JSONObject resultObject = new JSONObject(result);
                    int error = resultObject.getInt("error");
                    if (error != 0) {
                        String error_msg = resultObject.getString("error_msg");
                        Toast.makeText(MainActivity.this, error_msg, Toast.LENGTH_LONG).show();
                        return;
                    }
                    String app_id = resultObject.getString("app_id");
                    String channel_key = resultObject.getString("channel_key");
                    String channel_name_code = resultObject.getString("channel_name");
                    IS_CloseSelfAudioAndVideo = resultObject.getInt("observer") == 1;
                    Intent i = new Intent(MainActivity.this, ChatActivity.class);
                    i.putExtra(ConstantApp.ACTION_KEY_CHANNEL_NAME, channel_name);
                    i.putExtra(ConstantApp.KEY_CHANNEL_NAMECODE, channel_name_code);
                    i.putExtra(ConstantApp.KEY_CHANNEL_KEY, channel_key);
                    Lg.d("Integer.parseInt(uid)="+Integer.parseInt(uid));
                    i.putExtra(ConstantApp.KEY_USER_ID, Integer.parseInt(uid));
//                    i.putExtra(ConstantApp.KEY_USER_ID, uid);
                    i.putExtra(ConstantApp.KEY_APPID, app_id);
                    i.putExtra(ConstantApp.ACTION_KEY_ENCRYPTION_MODE, getResources().getStringArray(R.array.encryption_mode_values)[vSettings().mEncryptionModeIndex]);

                    startActivity(i);
                    finish();
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
    }

    public static boolean IS_CloseSelfAudioAndVideo = false;

    //LGY end


    public void forwardToSettings() {
        Intent i = new Intent(this, SettingsActivity.class);
        startActivity(i);
    }


    //LGY start
    String uid, channel_name;
    //LGY end
}
